# -*- coding: utf-8 -*-
"""用户个人信息"""
from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request

from info import db
from info.constants import QINIU_DOMIN_PREFIX, USER_COLLECTION_MAX_NEWS, USER_FOLLOWED_MAX_COUNT
from info.models import Category, News, User
from info.modules.profile import user_blue
from info.utills.captcha.response_code import RET
from info.utills.common import check_user_login
from info.utills.storage.image_storage import storage


@user_blue.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1. 取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.paginate(page, USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@user_blue.route('/other_info')
@check_user_login
def other_info():
    user = g.user

    # 去查询其他人的用户信息
    other_id = request.args.get("user_id")

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if other and user:
        # if user 是否关注过 news.user
        if other in user.followed:
            is_followed = True

    data = {
        "is_followed": is_followed,
        "user": g.user.to_dict() if g.user else None,
        "other_info": other.to_dict()
    }
    return render_template('news/other.html', data=data)


@user_blue.route('/user_follow')
@check_user_login
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 取到当前登录用户
    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())

    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('news/user_follow.html', data=data)


@user_blue.route('/news_list')
@check_user_login
def news_list():
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    try:
        paginate = News.query.filter(News.user_id == user.id).order_by(News.create_time.desc()).paginate(page,
                                                                                                         USER_COLLECTION_MAX_NEWS,
                                                                                                         False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    news_list_model = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news = [new.to_review_dict() for new in news_list_model]
    data = {
        "news": news,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template('news/user_news_list.html', data=data)


@user_blue.route('/news_release', methods=['POST', 'GET'])
@check_user_login
def news_release():
    if request.method == 'GET':
        # 渲染分类信息
        categories = []
        try:
            categories = Category.query.filter(Category.id != 1).all()
        except Exception as e:
            current_app.logger.error(e)

        categories_list = [category.to_dict() for category in categories]
        return render_template('news/user_news_release.html', categories_list=categories_list)
    # 发布新闻
    # 获取数据
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    source = '个人发布'
    # 校验参数
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 取到图片上传到七牛
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="图片上传失败")
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1
    # 将模型对象添加到数据库
    db.session.add(news)
    return jsonify(errno=RET.OK, errmsg="OK")


@user_blue.route('/use_collection')
@check_user_login
def use_collection():
    user = g.user
    # 获取页数
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    paginate = user.collection_news.paginate(page, USER_COLLECTION_MAX_NEWS, False)
    current_page = paginate.page
    total_page = paginate.pages
    news_list_model = paginate.items
    news_list = [news.to_basic_dict() for news in news_list_model]
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "collections": news_list
    }
    return render_template('news/user_collection.html', data=data)


@user_blue.route('/pass_info', methods=['GET', 'POST'])
@check_user_login
def pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 获取数据
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    if not all(['old_password', 'new_password']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    user.password = new_password
    return jsonify(errno=RET.OK, errmsg="修改成功")


@user_blue.route('/pic_info', methods=['GET', 'POST'])
@check_user_login
def pic_info():
    user = g.user
    if request.method == 'GET':
        data = {
            "user": g.user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)
    # post请求为修改头像
    # 获取到要上传的图片
    try:
        avatar = request.files.get('avatar')
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 上传到七牛云
    try:
        key = storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="文件上传失败")
    # 将图片地址保存在数据库
    user.avatar_url = key
    data = {
        "avatar_url": QINIU_DOMIN_PREFIX + key
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@user_blue.route('/base_info', methods=['GET', 'POST'])
@check_user_login
def base_info():
    """显示用户基本信息"""
    if request.method == 'GET':
        data = {
            "user": g.user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # 获取数据nick_name，signature，gender
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 校验数据
    if not all(['nick_name', 'signature', 'gender']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 查询再装饰器中查过了，只需要从g变量中取出修改就好了
    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    return jsonify(errno=RET.OK, errmsg="OK")


@user_blue.route('/user_info')
@check_user_login
def user_info():
    """显示用户基本信息"""
    user = g.user
    if not user:
        return redirect('/')
    data = {
        "user": user.to_dict()
    }
    return render_template('news/user.html', data=data)
